package logic

import (
	"context"
	"errors"
	"home-view/models/cache"
	"home-view/models/mysql"

	"home-view/homerpc/homerpc"
	"home-view/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ResetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewResetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ResetPasswordLogic {
	return &ResetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ResetPasswordLogic) ResetPassword(in *homerpc.ResetPasswordRequest) (*homerpc.ResetPasswordResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	if err := user.FindUserByPhone(mysql.DB, in.Phone); err != nil {
		return nil, err
	}
	if user.ID == 0 {
		return nil, errors.New("手机号不存在")
	}
	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Phone).Result()
	if result == "" {
		return nil, errors.New("你还没发送验证码")
	}
	if result != in.SendSmsCode {
		return nil, errors.New("验证码错误")
	}
	user.Password = in.Password

	if err := user.UserUpdate(mysql.DB, in.Phone); err != nil {
		return nil, err
	}

	return &homerpc.ResetPasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
